#include "animation.h"
#include <QColor>
#include <QPalette>
Animation::Animation()
{
    setupUI();
}

void Animation::setupUI(){
    this->setWindowTitle("Qt Animation");
    this->resize(400, 300);
    rect = new QLabel(this);
    rect->setFixedSize(50,50);
    rect->setStyleSheet("background-color: blue; border-radius: 15px");
    moveButton = new QPushButton("移动", this);
    colorButton = new QPushButton("改变颜色", this);
    resetButton = new QPushButton("复位", this);
    QHBoxLayout* headLayout = new QHBoxLayout();
    headLayout->addWidget(moveButton);
    headLayout->addWidget(colorButton);
    headLayout->addWidget(resetButton);
    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->addLayout(headLayout);
    mainLayout->addWidget(rect);

    QWidget* centralWidget = new QWidget(this);
    centralWidget->setLayout(mainLayout);
    setCentralWidget(centralWidget);

    mMove = new QPropertyAnimation(rect,"geometry");
    mReset = new QPropertyAnimation(rect,"geometry");

    connect(moveButton, &QPushButton::clicked, this, &Animation::move);
    connect(colorButton, &QPushButton::clicked, this, &Animation::changeColor);
    connect(resetButton, &QPushButton::clicked, this, &Animation::reset);
}

void Animation::changeColor(){
    QColor startColor = QColor(Qt::blue);
    QColor endColor = QColor(Qt::red);
    QPalette pale = rect->palette();
    mColor = new QPropertyAnimation(rect, "background-color");
    mColor->setDuration(1000);
    mColor->setStartValue(startColor);
    mColor->setEndValue(endColor);
    connect(mColor, &QPropertyAnimation::valueChanged, this, [=](const QVariant& val){
        QColor color = val.value<QColor>();
        rect->setStyleSheet(QString("background-color: %1; border-radius: 15px").arg(color.name()));
    });
    mColor->start();
}

void Animation::move(){
    mMove->setDuration(1000);
    mMove->setStartValue(QRect{20,180,50,50});
    mMove->setEndValue(QRect(rect->x()+200,rect->y(),rect->width(),rect->height()));
    mMove->start();
}

void Animation::reset(){
    mReset->setDuration(1000);
    mReset->setStartValue(QRect(rect->geometry()));
    mReset->setEndValue(QRect{20,180,50,50});
    mReset->start();
}
